const mongoose = require('mongoose')
const Movie = mongoose.model('movie')
const User = mongoose.model('user')
const { formatBody } = require('../tools')

module.exports = {
  /**
   * 获取电影列表
   */
  async list (ctx) {
    let page = ctx.query.page || 1
    let pageSize = ctx.query.pageSize || 20
    let type = ctx.query.type || ''
    let keyword = ctx.query.keyword || ''
    let movies, query
    if (keyword) {
      query = { title: { $regex: keyword, $options: '$i' } }
      if (type) {
        query = { $and: [{ type: type + '' }, { title: { $regex: keyword, $options: '$i' }}] }
      }
    } else {
      query = {type: type + ''}
      if (!type) query = {}
    }
    movies = await Movie.find(query, {
      type: 1, title: 1, poster: 1, views: 1, 'meta.updatedAt': 1
    })
    .sort({ 'meta.updatedAt': -1 })
    .limit(+pageSize).skip(+pageSize * (+page - 1))
    let count = await Movie.find(query).countDocuments()
    let data = formatBody(1, 'ok', movies)
    data.total = count
    return ctx.body = data
  },
  /**
   * 获取电影详情
   */
  async detail (ctx) {
    let { _id } = ctx.request.query
    if (!_id) return ctx.body = formatBody(0, '_id不可为空')
    let movie = await Movie.findOne({
      _id
    })
    if (!movie) {
      return ctx.body = formatBody(0, '不存在此电影')
    } else {
      await Movie.updateOne({ _id }, {
        views: movie.views + 1
      })
      return ctx.body = formatBody(1, 'ok', movie)
    }
  },
  /**
   * 获取我的收藏
   */
  async listCollection (ctx) {
    let { _id } = ctx.request.body
    if (!_id) return ctx.body = formatBody(0, '用户_id不可为空')
    let user = await User.findOne({
      _id
    }, {
      movieCollection: 1,
    }).populate({
      path: 'movieCollection',
      select: '_id title poster'
    })
    if (!user) {
      return ctx.body = formatBody(0, '用户不存在')
    } else {
      return ctx.body = formatBody(1, 'ok', user.movieCollection)
    }
  },
  /**
   * type = 1 -> 收藏 type = -1 -> 取消收藏
   */
  async collection (ctx) {
    let { _id, uid, type} = ctx.request.body
    if (!_id || !uid) return ctx.body = formatBody(0, '_id,uid不可为空')
    let movie = await Movie.findOne({
      _id
    })
    let user = await User.findOne({
      _id: uid
    })
    if (!movie) {
      return ctx.body = formatBody(0, '不存在此电影')
    } else if (!user) {
      return ctx.body = formatBody(0, '用户不存在')
    } else {
      let index = user.movieCollection.indexOf(_id)
      let len = user.movieCollection.length
      if (+type === 1) {
        if (len >= 50) {
          return ctx.body = formatBody(0, '最多只能收藏50部电影')
        }
        if (index < 0) {
          user.movieCollection.push(_id)
          await User.update({
            _id: uid
          }, {
            movieCollection: user.movieCollection
          })
          return ctx.body = formatBody(1, 'ok')
        } else {
          return ctx.body = formatBody(0, '已经收藏过该电影')
        }
      } else {
        if (index < 0) {
          return ctx.body = formatBody(0, '您并未收藏此电影')
        } else {
          user.movieCollection.splice(index, 1)
          await User.update({
            _id: uid
          }, {
            movieCollection: user.movieCollection
          })
          return ctx.body = formatBody(1, 'ok')
        }
      }
    }
  },
  /**
   * 删除所有电影
   */
  async clearAll (ctx) {
    await Movie.remove()
    return ctx.body = formatBody(1, '删除成功', {})
  },
  /**
   * 删除一部电影
   */
  async delete (ctx) {
    const movie = await Movie.find({
      id: ctx.query.id
    })
    if (movie.length > 0) {
      await Movie.deleteOne({ id: ctx.query.id })
      return ctx.body = formatBody(1, 'ok', movie)
    }
    return ctx.body = formatBody(0, '不存在该电影，无法进行删除操作')
  },
  /**
   * 更新电影信息
   */
  async update (ctx) {
    console.log('99999999')
    const { _id, type, title } = ctx.request.query
    const movie = await Movie.findOne({ _id })
    console.log('1', _id)
    if (movie) {
      await Movie.updateOne({
        _id
      }, {
        type, title
      })
      return ctx.body = formatBody(1, '更新成功')
    }
    return ctx.body = formatBody(0, '不存在该电影，无法进行更新操作')
  }
}
